<template>
  <view class="bg-gray" style="min-height:100vh">

    <view class="grid col-3 bg-white">
      <view class="nav-cus" :class="{'active': filter == 0}" @click="filter = 0">全部</view>
      <view class="nav-cus" :class="{'active': filter == 1}" @click="filter = 1">已缴费</view>
      <view class="nav-cus" :class="{'active': filter == 2}" @click="filter = 2">已检测</view>
    </view>

    <view v-show="filter == 0 || filter == 1" class="padding-lg">
      <view class="text-gray">
        <text class="text-sm">
          若已支付完成，请点击按钮刷新订单状态
        </text>
        <text class="cu-btn cuIcon cuIcon-refresh"></text>
      </view>
      
      <view v-for="(it,i) in pageList" :key="i" class="margin-top bg-white" style="border-radius:4px">
        <view class="padding-sm flex align-center" style="border-bottom:1px solid #eee">
          <view>
            <text class="text-bold">订单号：</text>
            <text>{{it.orderNO}}</text>
          </view>

          <view v-if="canPay(it)" @click="onRefreshOrder(it)" class="cu-btn cuIcon cuIcon-refresh" style="margin-left:auto;margin-right:5px"></view>
          <view class="tag-btn">{{getStatusAsString(it.orderStatus)}}</view>
        </view>
        <view class="padding-sm" style="position:relative">
          <view class="padding-tb-xs">
            <text class="margin-right">{{it.uname}}</text>
            <text class="margin-right">{{getSexAsString(it.sex)}}</text>
            <!-- <text class="margin-right">{{it.age}}岁</text> -->
          </view>
          <!-- <view class="padding-tb-xs">
            <text class="margin-right">检测科室：</text>
            <text class="margin-right">{{it.keshi}}</text>
          </view> -->
          <view class="padding-tb-xs">
            <text class="margin-right">检测项目：</text>
            <text class="margin-right">{{it.item_name}}</text>
          </view>
          <view class="padding-tb-xs">
            <text class="margin-right">核酸类别：</text>
            <text class="margin-right">{{it.category_name}}</text>
          </view>
          <view class="padding-tb-xs">
            <text class="margin-right">预约日期：</text>
            <text class="margin-right">{{it.orderDate}}</text>
          </view>
          <view class="padding-tb-xs">
            <text class="margin-right">申请日期：</text>
            <text class="margin-right">{{it.applyDate}}</text>
          </view>

          <view @click="onDisplayQr(it)" class="display-qr">
            <view class="qr">
              <image :src="it.qrcode" style="width:100%;height:100%"></image>
            </view>
            <view class="text-center">预约码</view>
          </view>
        </view>
        <view class="flex">
          <view v-if="canCancel(it)" class="padding-sm text-center text-primary" @click="onCancelOrder(it)">取消预约</view>
          <view v-if="canPay(it)" class="padding-sm text-center text-primary" @click="onPay(it)">继续支付</view>
          <view v-if="canPrint(it)" class="padding-sm text-center text-primary" @click="onPrintOrder(it)">打印发票</view>
        </view>
      </view>
    </view>

    <view v-show="filter == 2" class="padding-lg">
      <view v-for="(it,i) in pageList" :key="i" class="margin-top bg-white" style="border-radius:4px">
        <view class="padding-sm flex align-center" style="border-bottom:1px solid #eee">
          <view>
            <text class="text-bold">身份证号：</text>
            <text>{{it.idnum}}</text>
          </view>
        </view>
        <view class="padding-sm" style="position:relative">
          <view class="padding-tb-xs">
            <text class="margin-right">{{it.uname}}</text>
            <text class="margin-right">{{getSexAsString(it.sex)}}</text>
          </view>
          <view class="padding-tb-xs">
            <text class="margin-right">检测项目：</text>
            <text class="margin-right">{{it.item_name}}</text>
          </view>
          <view class="padding-tb-xs">
            <text class="margin-right">核酸类别：</text>
            <text class="margin-right">{{it.category_name}}</text>
          </view>
          <view class="padding-tb-xs">
            <text class="margin-right">检测结果：</text>
            <text class="margin-right">{{it.resultAsString}}</text>
          </view>
          <view class="padding-tb-xs">
            <text class="margin-right">采集时间：</text>
            <text class="margin-right">{{it.collect_time}}</text>
          </view>
          <view class="padding-tb-xs">
            <text class="margin-right">报告时间：</text>
            <text class="margin-right">{{it.report_time}}</text>
          </view>
        </view>
        <view class="flex">
          <view class="padding-sm text-center text-primary" @click="gotoReport(it)">查看报告</view>
        </view>
      </view>
    </view>

    <uni-popup ref="popupIdInput" type="dialog" :mask-click="false">
      <view class="card bg-white padding-xl" style="width:80vw;border-radius:10px">
        <view class="padding-tb">
          <view class="i-input">
            <input type="text" v-model="filterIdInput" placeholder="请输入身份证号查询" />
          </view>
        </view>
        <view class="margin-top flex">
          <button class="cu-btn lg bg-primary" @click="onSearch" style="flex:1">确定</button>
          <button class="cu-btn lg margin-left" @click="onCloseIdInput" style="flex:1">取消</button>
        </view>
      </view>
    </uni-popup>

    <uni-popup ref="popupQr" type="dialog">
      <view class="card bg-white flex justify-center padding-lg" style="width:80vw;border-radius:4px;">
        <!-- TODO: -->
        <image :src="displayQrSrc" style="width:240px;height:240px;background:#e0e0e0;"></image>
      </view>
    </uni-popup>
    <uni-popup ref="popupPrint" type="dialog">
      <view class="card bg-white flex justify-center padding-lg" style="width:80vw;border-radius:4px;">
        <!-- TODO: -->
        <image :src="printQrSrc" style="width:240px;height:240px;background:#e0e0e0;"></image>
      </view>
    </uni-popup>

    <cu-bar></cu-bar>
  </view>
</template>

<script>
import moment from 'moment'
import CheckAuthMixin from '@/mixins/CheckAuthMixin'
import PayMixin from '@/mixins/PayMixin'
import checkIdCard from '@/libs/checkIdCard' 
import uniPopup from '@/components/uni-popup/uni-popup.vue'

const CACHE_KEY = 'ts_matters_submiting'

export default {
  mixins: [
    CheckAuthMixin,
    PayMixin,
  ],
  components: {
    uniPopup,
  },
  data() {
    return {
      labelStyles: {
        minWidth: '80px',
        textAlign: 'justify',
        paddingRight: '30upx',
        fontSize: '30upx',
        color: 'inherit',
      },
      loading: false,
      filter: 0,
      filterIdInput: '',
      displayQrSrc: '',
      printQrSrc: '',

      totalCount: 0,
      pageSize: 20,
      pageNum: 1,
      pageList: [], /* [...Object.keys(Array.from(new Array(3)))].map(i => ({
        avatar: '/api/Images/headicons/teacher1_1.png',
        name: '赵诗诗',
        schoolName: '华发实验小学',
        fuel: 100,
      })), */

      // 0=预约中,1=线上已缴费,2=社保卡已缴费,3=已采样,4=退费作废,=超期作废,5=无法采集,6=超期作废
      orderStatusOpts: [
        { label: '预约中', value: '0'},
        { label: '线上已缴费', value: '1'},
        { label: '线下已缴费', value: '2'},
        { label: '已采样', value: '3'},
        { label: '退费作废', value: '4'},
        // { label: '超期作废', value: ''},
        { label: '无法采集', value: '5'},
        { label: '超期作废', value: '6'},
      ],
      sexOpts: [
        { label: '男', value: '1'},
        { label: '女', value: '2'},
      ],
      // categoryOpts: [
      //   { label: '混合（多少人次）', value: '0'},
      //   { label: '单人单管', value: '1'},
      // ],
      resultOpts: [
        { label: '阴性', value: '0' },
        { label: '疑似', value: '1' },
        { label: '阳性', value: '2' },
      ],
    }
  },
  watch: {
    loading(val) {
      if (val) {
        uni.showLoading()
      } else {
        uni.hideLoading()
      }
    },
    filter(type) {
      /**
       * TODO:
       */
      this.pageList = []
      this.pageNum = 1
      this.getPageData()
    },
  },
  onLoad(opts) {
    if (true || process.env.NODE_ENV == 'production') {
      this.loadState()

      setTimeout(() => {
        this.onShowIdInput()
      }, 333);
    } else {
      setTimeout(() => {
        // this.filterIdInput = '130282199207255111'
        this.filterIdInput = '130203197609110615'
        this.onSearch()
      }, 333)
    }
  },
  mounted() {
  },
  methods: {
    onRefreshOrder(it) {
      this.$http({
        url: `/api/Bank/Status?orders_id=${it.orders_id}`,
        method: 'POST',
        success: (res) => {
          if (res.success) {
            this.pageList = []
            this.pageNum = 1
            this.getPageData()
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        }
      })
    },
    canPay(it) {
      // console.log('----', it)
      return ['0'].indexOf(it.status) > -1 && Number(it.price) > 0
    },
    onPay(it) {
      if (Number(it.price) > 0) {
        this.gotoPay(it.orders_id)
      } else {
        uni.navigateTo({
          url: '/pages/hesuanyuyue/records/index'
        })
      }
    },
    canCancel(it) {
      return ['1','5'].indexOf(it.status) > -1 
        // && it.medicare == 0 // 不是医保
    },
    onCancelOrder(it) {
      if (it.medicare !== 0) { // 使用医保支付
        uni.showModal({
          title:'医保支付请到现场退款',
          showCancel: false
        })
      } else {
        this.loading = true

        this.$http({
          url: `/api/Book/Cancel?orders_id=${it.orders_id}`,
          method: 'POST',
          success: (res) => {
            if (res.success) {
              uni.showToast({
                title: '退款成功',
              })
              this.pageList = []
              this.pageNum = 1
              this.getPageData()
            } else {
              uni.showToast({
                title: res.msg,
                icon: 'none'
              })
            }
          },
          complete: (res) => {
            this.loading = false
          }
        })
      }
    },
    canPrint(it) {
      return ['1','3'].indexOf(it.status) > -1 
        && it.medicare == 0 // 不是医保
    },
    onPrintOrder(it) {
      this.$http({
        url: `/api/Invoice/Query?orders_id=${it.orders_id}`,
        method: 'POST',
        success: (res) => {
          if (res.success) {
            this.printQrSrc = `data:image/png;base64,${res.data.qrcode}`
            this.$refs.popupPrint.open()
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        }
      })
    },
    onShowIdInput() {
      this.$refs.popupIdInput.open()
    },
    onSearch() {
      // if (!checkIdCard(this.filterIdInput)) {
      //   uni.showToast({
      //     title: '请输入正确的身份证号',
      //     icon: 'none',
      //   })
      //   return;
      // }

      /**
       * FIXME:
       */
      this.onCloseIdInput()
      this.getPageData()
    },
    onCloseIdInput() {
      this.$refs.popupIdInput.close()
    },
    onDisplayQr(it) {
      /**
       * TODO:
       */
      this.displayQrSrc = it.qrcode
      this.$refs.popupQr.open()
    },
    getStatusAsString(val) {
      return (this.orderStatusOpts.find(x => x.value == val) || {}).label
    },
    getSexAsString(val) {
      return (this.sexOpts.find(x => x.value == val) || {}).label
    },
    getCategoryAsString(val) {
      return (this.categoryOpts.find(x => x.value == val) || {}).label
    },
    getPageData() {
      if (this.filter == 0) { // 全部
        this.getYuyue()
      } else if (this.filter == 1) { // 已缴费
        this.getYuyue(['1','2','3','4','5'])
      } else if (this.filter == 2) { // 已检测
        this.getJieguo()
      }
    },
    getYuyue(statusList) {
      this.loading = true

      /**
       * 查询预约信息
       */
      this.$http({
        url: '/api/Book/Query',
        method: 'POST',
        data: {
          idnum: this.filterIdInput,
          pageIndex: this.pageNum,
          pageSize: this.pageSize,
          status: statusList,
          // SkipCount: (this.pageNum - 1) * this.pageSize,
          // MaxResultCount: this.pageSize,
        },
        success: (res) => {
          if (res.success) {
            const { totalCount, items } = res.data
            this.totalCount = totalCount

            this.pageList = this.pageList.concat(
              items.map(x => {
                const {
                  appo_date, //: "2022-05-13T00:00:00"
                  idnum, //: "130282199207255111"
                  item_name, //: "新冠病毒核酸检测（常规）"
                  type_name, 
                  patient_name, //: "孟李辉"
                  price, //: 19.7
                  ins_time, 
                  range, //: "08:00-09:00"
                  sex, //: "1"
                  status, //: "0"
                  qrcode,
                  appo_id,
                  orders_id,
                  medicare, // 是否医保缴费
                } = x
                return {
                  orderNO: orders_id,
                  orders_id,
                  orderStatus: status,
                  status,
                  uname: patient_name,
                  price,
                  sex,
                  // age: 30,
                  // keshi: '核酸检测门诊',
                  // category: '0', // 
                  item_name,
                  category_name: type_name,
                  // 预约日期
                  orderDate: `${appo_date.substring(0,10)} ${range}`,
                  // 申请日期
                  applyDate: moment(ins_time).format('YYYY-MM-DD HH:mm'),
                  qrcode: `data:image/png;base64,${qrcode}`,
                  medicare,
                }
              })
              
              // [...Object.keys(Array.from(new Array(this.pageSize)))]
              //   .map(i => ({
              //     orderNO: '11111111',
              //     orderStatus: '1',
              //     uname: '张珊珊',
              //     sex: '1',
              //     age: 30,
              //     keshi: '核酸检测门诊',
              //     category: '0', // 
              //     // 预约日期
              //     orderDate: moment().add(2, 'days').format('YYYY-MM-DD HH:mm'),
              //     // 申请日期
              //     applyDate: moment().format('YYYY-MM-DD HH:mm'),
              //   }))
            )
          }
        },
        complete: () => {
          this.loading = false
        }
      })
    },
    getJieguo() {
      /**
       * TODO:
       * 查询检测结果
       */
      this.$http({
        url: '/api/SampleResult/Query',
        method: 'POST',
        data: {
          idnum: this.filterIdInput,
          pageIndex: this.pageNum,
          pageSize: this.pageSize,
        },
        success: (res) => {
          if (res.success) {
            const { totalCount, items } = res.data
            this.totalCount = totalCount

            this.pageList = this.pageList.concat(
              items.map(x => {
                const {
                  addr, // : "河北省唐山市"
                  collect_time, // : "2022-05-15T11:08:34.71"
                  idnum, // : "130282199207255111"
                  intime, // : "2022-05-15T18:31:45"
                  item_name, // : "新冠病毒核酸检测（常规）"
                  pat_name, // : "孟李辉"
                  report_time, // : "2022-05-15T20:58:36"
                  result, // : "0"
                  sex, // : "1"
                  tel, // : "15081515272"
                  type_name, // : "1:1（单人单管）"
                  orders_id,
                } = x
                return {
                  uname: pat_name,
                  addr,
                  collect_time: moment(collect_time).format('YYYY-MM-DD HH:mm:ss'),
                  idnum,
                  intime: moment(intime).format('YYYY-MM-DD HH:mm:ss'),
                  item_name,
                  report_time: moment(report_time).format('YYYY-MM-DD HH:mm:ss'),
                  result,
                  resultAsString: (this.resultOpts.find(x => x.value == result) || {}).label,
                  sex,
                  tel,
                  category_name: type_name,
                  orders_id,
                }
              })
            )
          }
        }
      })
    },
    gotoReport(it) {
      this.$utils.tempPageData.set(it, 'report_data')
      
      uni.navigateTo({
        url: `/pages/hesuanyuyue/records/report?orders_id=${it.orders_id}`,
      })
    },
    loadState() {
      const cached = this.$utils.tempPageData.get(CACHE_KEY)
      if (cached) {
        this.filterIdInput = cached.idno || ''
      }
    },
  },
  onReachBottom() {
    if (!this.loading && this.totalCount > this.pageSize * this.pageNum) {
      this.pageNum++
      this.getPageData()
    }
  },
}
</script>

<style scoped>
.bg-cus-blue {
  background: #3182F8;
}
.nav-cus {
  text-align: center;
  padding: 12px;
  font-size: 16px;
  position: relative;
}
.nav-cus.active {
  color: #3182F8;
}
.nav-cus.active::after {
  content: "";
  position: absolute;
  width: 20px;
  height: 4px;
  border-radius: 2px;
  background: #3182F8;
  bottom: 0;
  left: 50%;
  transform: translate(-50%,0);
}
.tag-btn {
  margin-left: auto;
  color: #3182F8;
  background: #ebf3fe;
  padding: 5px 10px;
  border-radius: 50px;
  white-space: nowrap;
}
.display-qr {
  position: absolute;
  right: 10px;
  top: 20px;
}
.qr {
  width: 40px;
  height: 40px;
  background: green;
  margin: 0 auto 5px;
}
</style>